package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Borrow;
import com.itheima.pojo.User;
import com.itheima.service.BookBorrowService;
import com.itheima.service.BookReturnService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

@RestController
@RequestMapping("/bookreturn")
public class BookReturnController {
    @Reference
    private BookReturnService returnService;
    @Reference
    private BookBorrowService borrowService;
    //分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        PageResult pageResult = returnService.pageQuery(queryPageBean);

        return pageResult;
    }
    @RequestMapping("/findById")
    public Result findById(@RequestBody Borrow borrow){
        String book_id2 = borrow.getBook_id();
        Integer book_id = Integer.parseInt(book_id2);
        Borrow borrow1 =  returnService.findById(book_id);
        String loan = borrow1.getLoan_card_id();
        return new Result(true,"成功",loan);
    }
    @RequestMapping("/returnbook")
    public Result returnbook(@RequestBody Borrow borrow){
        try {
            Integer book_id = Integer.parseInt(borrow.getBook_id());
            Borrow borrow1 =  returnService.findById(book_id);
            Date date1 = borrow1.getBorrow_time();
            Date date2 = borrow1.getEnd_time();
            Date date = new Date();
            returnService.delete(book_id);
            returnService.update(book_id);
            borrow1.setReturn_time(date);
            returnService.insert(borrow1);
            User user = borrowService.findByLoan(borrow1.getLoan_card_id());
            Integer number = user.getBorrowed_number();
            number= number-1;
            user.setBorrowed_number(number);
            returnService.updatenumber(user);
            return new Result(true,"归还成功");
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,"归还失败");
        }
    }
}
